package com.zjj.algorithm.learning.leetcode.tree;

import java.util.Stack;

/**
 * 114. 二叉树展开为链表 中档题
 * 给你二叉树的根结点 root ，请你将它展开为一个单链表：
 * <p>
 * 展开后的单链表应该同样使用 TreeNode ，其中 right 子指针指向链表中下一个结点，而左子指针始终为 null 。
 * 展开后的单链表应该与二叉树 先序遍历 顺序相同。
 * <p>
 * 输入：root = [1,2,5,3,4,null,6]
 * 输出：[1,null,2,null,3,null,4,null,5,null,6]
 * 示例 2：
 * <p>
 * 输入：root = []
 * 输出：[]
 * 示例 3：
 * <p>
 * 输入：root = [0]
 * 输出：[0]
 * <p>
 * <p>
 * 提示：
 * <p>
 * 树中结点数在范围 [0, 2000] 内
 * -100 <= Node.val <= 100
 * <p>
 * <p>
 * 进阶：你可以使用原地算法（O(1) 额外空间）展开这棵树吗？
 *
 * @author zjj_admin
 * @date 2022/12/14 9:46
 */
public class FlattenBinaryTreeToLinkedList {

    public static void main(String[] args) {

        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        TreeNode node6 = new TreeNode(6);

        node1.left = node2;
        node2.left = node3;
        node2.right = node4;
        node3.left = node5;

        flatten2(node1);

    }


    private static TreeNode head = null;



    public static void flatten2(TreeNode root) {
        traverse(root);
        System.out.println();
    }

    private static void traverse(TreeNode root) {
        if (root == null) {
            return;
        }
        TreeNode left = root.left;
        TreeNode right = root.right;
        if (head == null) {
            head = root;
        } else {
            head.right = root;
            head.left = null;
            head = head.right;
        }
        traverse(left);
        traverse(right);
    }


    /**
     * 时间
     * 1 ms
     * 击败
     * 21.25%
     * 内存
     * 41.1 MB
     * 击败
     * 47.74%
     *
     * @param root
     */
    public static void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            return;
        }
        TreeNode curr = root;
        Stack<TreeNode> stack = new Stack<>();
        while (true) {
            if (curr.left != null) {
                stack.push(curr.right);
                curr.right = curr.left;
                curr.left = null;
            }
            if (curr.right != null) {
                curr = curr.right;
            } else {
                if (stack.size() > 0) {
                    TreeNode pop = stack.pop();
                    if (pop != null) {
                        curr.right = pop;
                    }
                } else {
                    break;
                }
            }
        }

    }

}
